package com.myboot.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: 韦溜溜
 * @Description:
 * @Date: Create in 20:51 2019/3/13
 */
@Component
@Slf4j
public class RedisLockService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //上锁

    /**
     * @param key productId
     * @param value 当前时间+过期时间
     * @return
     */
    public boolean lock(String key,String value){
        if(redisTemplate.opsForValue().setIfAbsent(key, value)){
            //加锁成功
            return true;
        }
        //判断是否是死锁
        String currentTime = redisTemplate.opsForValue().get(key);
        if(!currentTime.isEmpty() &&
                Long.parseLong(currentTime)<System.currentTimeMillis() ){
            //查看是否先获取钥匙
            String oldTime = redisTemplate.opsForValue().getAndSet(key,value);
            if(!oldTime.isEmpty() && oldTime.equals(currentTime)){
                return true;
            }
        }
        return false;
    }

    //解锁

    /**
     *
     * @param key
     * @param value
     */
    public void unlock(String key , String value){
        String currentTime = redisTemplate.opsForValue().get(key);
        try {
            if (!currentTime.isEmpty() && currentTime.equals(value)){
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        }catch (Exception e){
            log.error("【redis分布式锁】解锁失败，{}" , e);
        }
    }
}
